import { IProduct,Cproduct } from "../../types/product";
interface IState {//list规范
    list: IProduct[],
    cartList:Cproduct[]
}
let initData: IState = {
    list: [] ,//商品列表
    cartList:[] //购物车列表
}
function getIndex(data:Cproduct[],id:number){
    return data.findIndex((item:Cproduct)=>item.id === id)
}
export default (state=initData, action:any) => {
    console.log(action)
    let newState = JSON.parse(JSON.stringify(state))
    switch (action.type) {
        case "Init_LIST":
            newState.list = action.list
            // return { ...state, list: [...action.list] }
            return newState
        case "ADD_TAR":
            let target = action.target
            let index = getIndex(newState.cartList , target.id)
            if(index!=-1){//已经有该商品
                newState.cartList[index].num++
            }else{
                //没有该商品
                target.num = 1; //数量
                target.checked = true; //选中
                newState.cartList.push(target);
            }
            return newState
        case "CHANGE_COUNT":
            newState.cartList.forEach((item:Cproduct)=>{
                if(item.id === action.id){
                    item.num = action.num
                }
            })
            return newState
        case "DEL_TARGET":
            //将要删除
            let i =  getIndex(newState.cartList , action.id)
            if(action.isDel){//要删除
                newState.cartList.splice(i,1)
            }
            else{
                let target = newState.cartList[i];
                target.num = action.num;
                newState.cartList[i] = {...target}
                return newState
            }
        default:
            return state
    }
}